package dnl.util.ui;

import java.awt.BorderLayout;
import java.awt.Window;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class ProgressDialog extends JDialog {

	private static final String TITLE = "Progress ...";

	private static Map<Integer, ProgressDialog> dialogsCache = new HashMap<Integer, ProgressDialog>();

	private JProgressBar progressBar = new JProgressBar();
	private JLabel label = new JLabel();

	public ProgressDialog(Window owner, String message, ModalityType modalityType) {
		super(owner, TITLE, modalityType);
		init(message);

	}

	public ProgressDialog(Window owner, String message) {
		super(owner, TITLE);
		init(message);
	}

	public void init(String message) {
		JPanel jp = new JPanel(new BorderLayout());
		jp.setBorder(BorderFactory.createLoweredBevelBorder());
		progressBar.setStringPainted(true);
		jp.add(BorderLayout.CENTER, progressBar);
		jp.add(label, BorderLayout.NORTH);
		label.setText(" " + message + ":  ");
		this.getContentPane().add(BorderLayout.CENTER, jp);
		this.pack();
	}

	public void showProgress(int progress) {
		progressBar.setValue(progress);
	}

	public static void finished(final Window owner) {
		Runnable r = new Runnable() {
			@Override
			public void run() {
				ProgressDialog dlg = dialogsCache.get(owner.hashCode());
				if (dlg != null) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				dlg.setVisible(false);
				dlg.dispose();
			}
		};
		SwingUtilities.invokeLater(r);
	}

	public static void setProgressText(final Window owner, String progressText) {
		ProgressDialog progressDialog = dialogsCache.get(owner.hashCode());
		if (progressDialog != null) {
			progressDialog.label.setText(progressText);
		}
	}

	public static void showProgress(final Window owner, final String message, final int progress) {
		// if (SwingUtilities.isEventDispatchThread()) {
		// throw new IllegalStateException(
		// "Do not call showProgress() from the event dispatch thread!");
		// }
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				ProgressDialog progressDialog = dialogsCache.get(owner.hashCode());
				if (progressDialog == null) {
					final ProgressDialog dlg = new ProgressDialog(owner, message,
							ModalityType.TOOLKIT_MODAL);
					progressDialog = dlg;
					dialogsCache.put(owner.hashCode(), dlg);
					WindowUtils.centerWindowRelative(progressDialog, owner);
					dlg.setVisible(true);
				}
				progressDialog.showProgress(progress);
				if (progress == 100) {
					finished(owner);
				}
			}
		});
	}

}
